import { HttpService } from './../../shared/service/http.service';
import { Component, OnInit, Input } from "@angular/core";
import { AlertController } from "@ionic/angular";
import { AppGlobalService } from "src/app/shared/service/app-global.service";
import { EventService } from 'src/app/shared/service/event.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';

@Component({
  selector: "app-job-manager",
  templateUrl: "./job-manager.component.html",
  styleUrls: ["./job-manager.component.scss"]
})
export class JobManagerComponent implements OnInit {
  @Input() tagData: any;
  defaultStyle: string;
  showIconLimit = 4; // 默认显示4个按钮
  isExpend = false; // 默认收起
  expendIconId = 'expendIconId';

  firstRowData: any[];
  secondRowData: any[];
  buttonArray: any[];
  constructor(
    private alertController: AlertController,
    private http: HttpService,
    private eventService: EventService,
    private pageModalService: PageModalService,
    private appGlobalService: AppGlobalService) { }

  ngOnInit() {
    this.defaultStyle = this.tagData.data.style ? this.tagData.data.style : "1";
    // 蜂喔商户1.6.33 新增可配置的图标个数
    if (this.tagData && this.tagData.data && this.tagData.data.data) {

      // console.log('showIconLimit=' + this.tagData.data.data.length);
      this.showIconLimit = this.tagData.data.data.length;
      this.expendIconId += new Date().getTime();
      if (this.tagData.data.link && this.tagData.data.link.params && this.tagData.data.link.params.iconLimitCount) {
        this.showIconLimit = this.tagData.data.link.params.iconLimitCount;
      }
      if (this.tagData.data.link
        && this.tagData.data.link.params.layoutType
        && this.tagData.data.link.params.layoutType) {
        const dataList = this.tagData.data.data;
        if (dataList.length > 0) {
          const firstRowIndex = Math.round(dataList.length / 2);
          this.firstRowData = [];
          this.secondRowData = [];
          this.firstRowData = dataList.slice(0, firstRowIndex);

          this.secondRowData = dataList.slice(firstRowIndex, dataList.length);
          if (this.secondRowData.length < this.firstRowData.length) {
            this.secondRowData.push({});
          }
          // 2024.10.23 检查如果带了buttonArrayStyle则给默认样式
          if (this.firstRowData.length > 0) {

            let btnIndex = 0;
            // tslint:disable-next-line:prefer-for-of
            for (let index = 0; index < this.firstRowData.length; index++) {
              const element = this.firstRowData[index];
              if (element.buttonArrayStyle !== undefined) {
                if (element.hasOwnProperty('buttonArrayStyle')) {
                  btnIndex = index;
                  break; // 找到后退出循环
                }
              }
            }

            if (this.firstRowData[btnIndex]
              && this.firstRowData[btnIndex].buttonArrayStyle !== undefined) {
              this.firstRowData[btnIndex].selected = 'true';
            }

          }
        }
      }
    }
  }

  clickAll(item, e?, data?) {

    if (data.submit) {
      const params = {
        content: data.submit.params,
        id: data.submit.id,
        sessionId: localStorage.getItem('sessionId')
      };
      this.http.post('application/submit', params, res => {
        // 请求数据成功
        if (res.success) {
          this.pageModalService.openPage(item);
        } else {
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
      });

    } else {
      if (e) {
        e.stopPropagation();
      }
      // 支持弹窗 1.6.34
      this.pageModalService.openPage(item);
    }
  }

  handleClick(item, tip?) {
    localStorage.setItem("clearInformationHallSubscriptionTag", "1");
    this.eventService.eventEmit.emit("clearInformationHallSubscription", "");
    
    // 2024.10.23 新增
    if (this.firstRowData
      && this.firstRowData.length > 0
      && item.hasOwnProperty('buttonArrayStyle')) {
      this.firstRowData.forEach((element) => {
        if (element.hasOwnProperty('buttonArrayStyle')) {
          element.selected = 'false';
        }
      });
      item.selected = 'true';
    }

    if (item.link && item.link.params && item.link.params.badge !== undefined) {
      item.link.params.badge = '0';
    }
    if (tip) {
      this.appGlobalService.showToast(tip ? tip : '正在快马加鞭开发中', 2000, "middle");
      return;
    }
    if (item.type === 'phone' && item.link.params && item.link.params.phone) {
      this.presentAlertConfirm(item.link.params.phone, '');
    } else {
      if (item.content && item.id) {
        const params = {
          content: item.content.params,
          id: item.id,
          sessionId: localStorage.getItem('sessionId')
        };
        // 请求获取新数据
        this.http.post('application/submit', params, res => {
          // 请求数据成功
          if (res.success) {
            this.pageModalService.openPage(item.link);
          } else {
            // this.pageModalService.openPage(item);
            // 请求数据失败
            this.appGlobalService.showToast(res.message, 2000, 'middle');
          }
        },
          err => {
            this.pageModalService.openPage(item.link);
            // 请求数据失败
            // this.appGlobalService.showToast(err.message, 2000, 'middle');
          });

      } else {
        if (item.eventName) {
          const param = {};
          if (item.eventParam && item.eventValue) {
            param[item.eventParam] = item.eventValue;
          }
          this.eventService.eventEmit.emit(item.eventName, param);
        } else {
          this.pageModalService.openPage(item.link);
        }
      }



      //   const sessionId = localStorage.getItem("sessionId");
      //   const pageParams = {
      //     pageId: item.target,
      //     params: item.params,
      //     sessionId
      //   };
      //   this.appGlobalService.goToForward(pageParams);
      // }
    }
  }

  async presentAlertConfirm(mobile, name, sureText?) {
    const alert = await this.alertController.create({
      header: '',
      message: name + " " + mobile,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary'
        }, {
          text: sureText ? sureText : '拨打',
          handler: () => {
            this.http.changeCallNumber(mobile);
          }
        }
      ]
    });
    await alert.present();
  }

  // 展开或者收起
  expend() {
    this.isExpend = !this.isExpend;
    const imgIcon = document.getElementById(this.expendIconId) as HTMLImageElement;
    if (imgIcon) {
      if (this.isExpend) {
        if (this.tagData.data && this.tagData.data.link && this.tagData.data.link.params && this.tagData.data.link.params.closeImagUrl) {
          imgIcon.src = this.tagData.data.link.params.closeImagUrl;
        }
        this.showIconLimit = this.tagData.data.data.length;
        // 收起
      } else {
        if (this.tagData.data && this.tagData.data.link && this.tagData.data.link.params && this.tagData.data.link.params.openImagUrl) {
          imgIcon.src = this.tagData.data.link.params.openImagUrl;
        }
        this.showIconLimit = this.tagData.data.link.params.iconLimitCount;
        // 展开
      }
    }
  }
}
